package com.atguigu.education.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.education.app.func.DimAsyncFunction;
import com.atguigu.education.bean.TradeProvinceBean;
import com.atguigu.education.util.ClickHouseUtil;
import com.atguigu.education.util.DateFormatUtil;
import com.atguigu.education.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @title: DwsTradeProvinceSumWindow
 * @Author Mr.Liu
 * @Date: 2022/9/4 9:13
 * @Version 1.0
 */
public class DwsTradeProvinseSumWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // TODO 2 设置状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
         */
        String orTopic = "dwd_trade_order_pre_process";
        String uqbuyTopic = "dwd_trade_unique_buyer_detail";
        String groupID = "dws_trade_province_sum_window";
        DataStreamSource<String> orderSource = env.addSource(KafkaUtil.getKafkaConsumer(orTopic, groupID));
        DataStreamSource<String> uniqueBuySource = env.addSource(KafkaUtil.getKafkaConsumer(uqbuyTopic, groupID));
        //order
        SingleOutputStreamOperator<JSONObject> jsonStream = orderSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(s);
                if (jsonObject != null){
                    if (jsonObject.getString("province_id") != null) {
                        collector.collect(jsonObject);
                    }
                }

            }
        });
        //订单数
        SingleOutputStreamOperator<TradeProvinceBean> orderCountStream = jsonStream.keyBy(s -> s.getString("order_id")).map(new MapFunction<JSONObject, TradeProvinceBean>() {
            @Override
            public TradeProvinceBean map(JSONObject jsonObject) throws Exception {

                return new TradeProvinceBean("", "", jsonObject.getString("province_id"), "",0L, 1L, 0.0, jsonObject.getLong("oi_ts"));
            }
        });
        //orderCountStream.print("order------");

        //总金额
        SingleOutputStreamOperator<TradeProvinceBean> amountStream = jsonStream.map(new MapFunction<JSONObject, TradeProvinceBean>() {
            @Override
            public TradeProvinceBean map(JSONObject jsonObject) throws Exception {
                return new TradeProvinceBean("", "", jsonObject.getString("province_id"), "",0L, 0L, Double.parseDouble(jsonObject.getString("final_amount")), jsonObject.getLong("oi_ts"));

            }
        });
        //独立下单人数


        SingleOutputStreamOperator<TradeProvinceBean> uniqueCountStream = uniqueBuySource.flatMap(new FlatMapFunction<String, TradeProvinceBean>() {
            @Override
            public void flatMap(String s, Collector<TradeProvinceBean> collector) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(s);
                if (jsonObject.getString("source_id") != null) {
                    TradeProvinceBean TradeProvinceBean = new TradeProvinceBean("", "", jsonObject.getString("province_id"), "",1L, 0L, 0.0, jsonObject.getLong("oi_ts"));
                    collector.collect(TradeProvinceBean);
                }
            }
        });

        //uniqueCountStream.print("unique-----");

        //连接

        DataStream<TradeProvinceBean> unionStream = orderCountStream.union(uniqueCountStream).union(amountStream);
        //unionStream.print("union");
        SingleOutputStreamOperator<TradeProvinceBean> filter = unionStream.filter(new FilterFunction<TradeProvinceBean>() {
            @Override
            public boolean filter(TradeProvinceBean TradeProvinceBean) throws Exception {
                boolean flag = false;
                if (TradeProvinceBean.getTs() != null && TradeProvinceBean.getProvince_id() != null) {
                    flag = true;
                }
                return flag;
            }
        });
       // unionStream.print("union-----------");
        //水位线
        filter.print("filter---");
        KeyedStream<TradeProvinceBean, String> keyBy = filter.keyBy(new KeySelector<TradeProvinceBean, String>() {
            @Override
            public String getKey(TradeProvinceBean TradeProvinceBean) throws Exception {
                return TradeProvinceBean.getProvince_id();
            }
        });

        //keyBy.print("keyby----------");
        SingleOutputStreamOperator<TradeProvinceBean> beanWithWatermarkStream = keyBy.assignTimestampsAndWatermarks(WatermarkStrategy.<TradeProvinceBean>forBoundedOutOfOrderness(Duration.ofSeconds(2L)).withTimestampAssigner(new SerializableTimestampAssigner<TradeProvinceBean>() {
            @Override
            public long extractTimestamp(TradeProvinceBean TradeProvinceBean, long l) {
                return TradeProvinceBean.getTs()*1000L;
            }
        }));


        //开窗

         //beanWithWatermarkStream.print("water");

        SingleOutputStreamOperator<TradeProvinceBean> reduceStream = beanWithWatermarkStream.windowAll(TumblingEventTimeWindows.of(Time.seconds(5L)))
                .reduce(new ReduceFunction<TradeProvinceBean>() {
                    @Override
                    public TradeProvinceBean reduce(TradeProvinceBean value1, TradeProvinceBean value2) throws Exception {
                        value1.setOrderCount(value1.getOrderCount() + value1.getOrderCount());
                        value1.setOrderUniqueUserCount(value1.getOrderUniqueUserCount() + value2.getOrderUniqueUserCount());
                        value1.setOrderAmount(value1.getOrderAmount()+value2.getOrderAmount());
                        return value1;
                    }
                }, new AllWindowFunction<TradeProvinceBean, TradeProvinceBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow timeWindow, Iterable<TradeProvinceBean> iterable, Collector<TradeProvinceBean> collector) throws Exception {
                        TradeProvinceBean TradeProvinceBean = iterable.iterator().next();
                        TradeProvinceBean.setStt(DateFormatUtil.toYmdHms(timeWindow.getStart()));
                        TradeProvinceBean.setEdt(DateFormatUtil.toYmdHms(timeWindow.getEnd()));
                        TradeProvinceBean.setTs(System.currentTimeMillis());
                        collector.collect(TradeProvinceBean);
                    }
                });

        //关联dim
        reduceStream.print("reduce");
        SingleOutputStreamOperator<TradeProvinceBean> sourceBeanStream = AsyncDataStream.unorderedWait(reduceStream, new DimAsyncFunction<TradeProvinceBean>("DIM_PROVINCE_FULL") {

            @Override
            public String getKey(TradeProvinceBean input) {
                return input.getProvince_id();
            }

            @Override
            public void join(TradeProvinceBean input, JSONObject obj) {
                input.setProvince_name(obj.getString("name"));
            }
        }, 100, TimeUnit.SECONDS);

        sourceBeanStream.print("bean......");
        sourceBeanStream.addSink(ClickHouseUtil.getClickHouseSinkFunc("insert into dws_trade_province_suc_window values(?,?,?,?,?,?,?,?)"));
        env.execute(groupID);
    }
}
